package com.hs.authcenter.config;

import com.hs.authcenter.enhancer.JwtTokenEnhancer;
import com.hs.authcenter.properties.JwtCAProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;

/**
 * @Description: TODO
 * @Author 胡尚
 * @Date: 2024/7/26 14:20
 */
@Configuration
@EnableConfigurationProperties(value = JwtCAProperties.class)
public class JwtTokenStoreConfig {

    /**
     * JWT 加密密钥key
     */
    private final String signingKey = "123123";

    /**
     * 注入证书properties配置信息
     */
    @Autowired
    private JwtCAProperties jwtCAProperties;

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        // 往Spring容器中添加一个JwtAccessTokenConverter类型的bean对象
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();

        // 使用对称加密方式
        // jwtAccessTokenConverter.setSigningKey(signingKey);

        //配置JWT使用的秘钥 非对称加密
        jwtAccessTokenConverter.setKeyPair(keyPair());

        return jwtAccessTokenConverter;
    }

    @Bean
    public TokenStore jwtTokenStore(){
        // 往Spring容器中添加一个TokenStore类型的Bean对象
        // 而 JwtTokenStore 需要用到上面方法中的JwtAccessTokenConverter
        return new JwtTokenStore(jwtAccessTokenConverter());

    }


    /**
     * 根据我们生成的证书，创建一个KeyPair对象
     * @return 非对称加密对象
     */
    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
                new ClassPathResource(jwtCAProperties.getKeyPairName()), jwtCAProperties.getKeyPairSecret().toCharArray());
        return keyStoreKeyFactory.getKeyPair(jwtCAProperties.getKeyPairAlias(), jwtCAProperties.getKeyPairStoreSecret().toCharArray());
    }

    /**
     * token的增强器 根据自己业务添加字段到Jwt中
     * @return
     */
    @Bean
    public JwtTokenEnhancer jwtTokenEnhancer() {
        return new JwtTokenEnhancer();
    }
}
